//
//  MJ_UserLoginViewModel.m
//  UEAssistant
//
//  Created by mac on 2017/12/27.
//  Copyright © 2017年 youyixinxi. All rights reserved.
//

#import "MJ_UserLoginViewModel.h"
#import "MJ_UserMessage.h"
#import "IPhoneType.h"
#import "NSString+RandomString.h"

@interface MJ_UserLoginViewModel ()

@property (strong, nonatomic)MJ_UserLoginModel *loginModel;

@end


@implementation MJ_UserLoginViewModel

- (MJ_UserLoginModel *)loginModel {
    if (!_loginModel) {
        _loginModel = [[MJ_UserLoginModel alloc] init];
    }
    return _loginModel;
}

- (MJ_UserLoginResult *)resultModel {
    if (!_resultModel) {
        _resultModel = [[MJ_UserLoginResult alloc] init];
    }
    return _resultModel;
}


- (void)initializeLoginWithParameter:(NSDictionary *)parameter Result:(LoginResultBlock)result {
    [AvailableNetWorking postWithUrl:login_connector params:parameter successHandler:^(id responseObject) {
        if (responseObject) {
            self.loginModel = [MJ_UserLoginModel mj_objectWithKeyValues:responseObject];
            
            if (self.loginModel.code == 200) {
                self.resultModel = self.loginModel.result;
                //保存账户信息到本地
                [self saveUserInfoWithModel:self.resultModel account:parameter[@"userName"] password:parameter[@"userPwd"]];
                result(YES);
                
            }else{
                result(NO);
                [TopAlertView SetUpbackgroundColor:AlertRedColor andStayTime:2.0 andImageName:@"imagePlaceholder" andTitleStr:self.loginModel.message andTitleColor:[UIColor whiteColor] andCancel:YES];
            }
        }
    } falureHandler:^(NSError *error) {
        [TopAlertView SetUpbackgroundColor:AlertRedColor andStayTime:2.0 andImageName:@"imagePlaceholder" andTitleStr:@"登录失败，请检查您的网络连接是否开启！" andTitleColor:[UIColor whiteColor] andCancel:YES];
         result(NO);
    }];
}


- (void)autoLoginWithResult:(LoginResultBlock)result {

//    NSString *uuidString = [[[UIDevice currentDevice].identifierForVendor UUIDString] stringByReplacingOccurrencesOfString:@"-" withString:@""];
    //随机生成32位Cookie
    [UserDefaults setObject:[NSString getRandomStringWithNum:32] forKey:@"User_Cookie"];
    TGLog(@"自动登录Cookie = %@",[UserDefaults objectForKey:@"User_Cookie"]);
    
    NSDictionary *parameter = @{@"userName":[UserDefaults objectForKey:@"account"],
                                @"userPwd":[UserDefaults objectForKey:@"password"],
                                @"deviceToken":[userManager getDeviceToken],
                                @"deviceModel":[IPhoneType iphoneType]};
    
    [AvailableNetWorking postWithUrl:login_connector params:parameter successHandler:^(id responseObject) {
        if (responseObject) {
            self.loginModel = [MJ_UserLoginModel mj_objectWithKeyValues:responseObject];
            
            if (self.loginModel.code == 200) {
                
                self.resultModel = self.loginModel.result;
                //保存账户信息到本地
                [self saveUserInfoWithModel:self.resultModel account:parameter[@"userName"] password:parameter[@"userPwd"]];
                
                result(YES);
                
            }else{
                result(NO);
                [TopAlertView SetUpbackgroundColor:AlertRedColor andStayTime:2.0 andImageName:@"imagePlaceholder" andTitleStr:self.loginModel.message andTitleColor:[UIColor whiteColor] andCancel:YES];
            }
        }
    } falureHandler:^(NSError *error) {
        result(NO);
        [TopAlertView SetUpbackgroundColor:AlertRedColor andStayTime:2.0 andImageName:@"imagePlaceholder" andTitleStr:@"拉取用户登录信息失败，请检查您的网络连接是否开启！" andTitleColor:[UIColor whiteColor] andCancel:YES];
    }];
}

//保存个人信息
- (void)saveUserInfoWithModel:(MJ_UserLoginResult *)model account:(NSString *)account password:(NSString *)password {
    //是否是平台译员池成员
    shareData.isPoolTranslator = model.isPoolTranslator;
    //保存头像
    shareData.headURL = model.facePath;
    //保存用户电话
    shareData.phone = model.userLoginDetail.phone;
    //更新头像
    [[MJ_UserMessage sharedInstance].userHeadButton setImageForState:UIControlStateNormal withURL:[NSURL URLWithString:model.facePath] placeholderImage:[UIImage imageNamed:@"user"]];
    //保存昵称
    shareData.userNick = model.userNick;
    //保存用户id
    shareData.userId = [NSString stringWithFormat:@"%.0f",model.userId];
    //保存登录用户的个人权限等级
    [UserDefaults setInteger:model.userLoginDetail.userType forKey:CurrentUserTypeKey];
    
    
    //保存账号密码
    [UserDefaults setObject:account forKey:@"account"];
    [UserDefaults setObject:password forKey:@"password"];
    //设定用户登录状态为1，即为在线
    [[MJ_UserMessage sharedInstance] userOnline];
}


@end
